package com.ztom.daily.n2022.m4;

/**
 * 按奇偶排序数组
 * <p>
 * https://leetcode-cn.com/problems/sort-array-by-parity/
 *
 * @author ZhangTao
 */
public class Day28SortArrayByParity {

    public int[] sortArrayByParity1(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }

        int n = nums.length;
        int[] res = new int[n];
        int l = 0, r = n - 1;
        for (int num : nums) {
            if ((num & 1) == 0) {
                res[l++] = num;
            } else {
                res[r--] = num;
            }
        }
        return res;
    }

    /**
     * 原地交换
     *
     * @param nums
     * @return
     */
    public int[] sortArrayByParity(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }

        int n = nums.length;
        int l = 0, r = n - 1;
        while (l < r) {
            while (l < r && (nums[l] & 1) ==0) {
                l++;
            }
            while (l < r && (nums[r] & 1) == 1) {
                r--;
            }
            if (l < r) {
                int tmp = nums[l];
                nums[l] = nums[r];
                nums[r] = tmp;
                l++;
                r--;
            }
        }
        return nums;
    }
}
